<template>
    <div class="familyman">
        <div class="search">
            <el-form :inline="true" :model="query" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="query.key" placeholder="参数名" clearable style="width: 240px;" />
                </el-form-item>
                <el-form-item>
                    <el-button color="#b9e8e3" plain class="btn" @click="getSearch">查询</el-button>
                    <el-button color="#17b3a3" class="btn2" @click="getAdd">新增</el-button>
                    <el-button color="#f56c6c" class="btn2" @click="getDelete(null)"
                        :disabled="delId.length == 0">批量删除</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table">
            <el-table ref="multipleTableRef" :data="tableData" highlight-current-row style="width: 100%"
                @selection-change="handleSelectionChange" border>
                <el-table-column type="selection" width="55" />
                <el-table-column property="code" label="项目编码" width="110" />
                <el-table-column property="name" label="项目名称" width="150" />
                <el-table-column property="createOn" label="创建时间" width="220" />
                <el-table-column property="createBy" label="创建人" width="150" />
                <el-table-column property="modifiedOn" label="修改时间" width="220" />
                <el-table-column property="modifiedBy" label="修改人" width="80" />
                <el-table-column property="remark" label="备注" width="100" />
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)" link
                            style="color: #17b3a3;">修改</el-button>
                        <el-button size="small" @click="handleDelete(scope.row)" link
                            style="color: #17b3a3;">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="dialogVisible" :title="title" width="800">
            <el-form ref="ruleFormRef" style="padding:30px 10px 10px" :model="ruleForm" :rules="rules"
                label-width="auto">

                <el-form-item label="项目编码" prop="code">
                    <el-input v-model="ruleForm.code" placeholder="项目编码" />
                </el-form-item>
                <el-form-item label="项目名称" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="项目名称" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="ruleForm.remark" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <page :query="query" :total="total" @size-change="sChange" @page-change="pChange"></page>
    </div>
</template>

<script lang="ts" setup>
import { list, add, userdel, detail, updata } from "@/api/biosample-project"
import { ref, reactive, onMounted } from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

interface TaskItem {
    id?: number,
    code: string,
    name: string,
    createOn?: string,
    createBy?: string,
    modifiedOn?: string,
    modifiedBy?: string,
    remark: string,
}

const ruleFormRef = ref<FormInstance | null>(null)
const form = reactive<TaskItem>({
    code: '',
    name: '',
    remark: '',
    t: Date.now(),
    createOn: '',
    createBy: '',
    modifiedUserId: '',
    modifiedOn: '',
    modifiedBy: '',
    createUserId: null,
    id: null ,
})
const options = ref([])

const rules = reactive<FormRules<RuleForm>>({
    code: [
        { required: true, message: '项目编码不能为空', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '项目名称不能为空', trigger: 'blur' },
    ]
})
const name = ref('')
const sourceIdCard = ref('')
const familyId = ref()
const size = ref<ComponentSize>('default')
const disabled = ref(false)
const multipleSelection = ref<User[]>([])
const delId = ref([])

// 函数：=========================================
// 多选
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
    delId.value = []
    for (const item of val) {
        delId.value.push(item.id)
    }
}
// 生命周期
onMounted(() => {
    getproject()
})
// 渲染表格数据
function getproject() {
    projectList(query).then(res => {
        // console.log(res, '888');
        tableData.value = res.page.list
        total.value = res.page.totalCount
    })
}
// 查询
function getSearch() {
    query.page = 1
    getproject()
}
// 分页
// 切换条数
const sChange = (val: number) => {
    console.log(`切换为每页：${val}条`);
    query.limit = val
    getproject()
}
// 切换页数
const pChange = (val: number) => {
    console.log(`第${val}页`);
    query.page = val
    getproject()
}
// 新增
function getAdd() {
    dialogVisible.value = true
    title.value = '新增'
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
}

function handleEdit(row: TaskItem) {
    formTitle.value = "编辑"
    dialogFormVisible.value = true
    currentId.value = row.id || null

    // 显示加载状态
    loading.value = true

    detail(row.id).then(res => {
        console.log(res, '数据');

        form.code = res.project.code
        form.name = res.project.name
        form.remark = res.project.remark
    })
        .catch(() => {
            ElMessage.error('获取详情失败')
            currentId.value = null
        })
        .finally(() => {
            loading.value = false
        })
}

function handleDelete(row: TaskItem) {
    if (row.id === undefined) {
        ElMessage.error('任务ID未定义');
        return;
    }

    ElMessageBox.confirm(`确定删除这${row.name}项目?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        userdel([row.id]).then(res => {
            console.log(res);
            ElMessage.success('删除成功');
            fetchData();
        }).catch(() => {
            ElMessage.error('删除失败');
        });
    }).catch(() => {
        // 取消删除
    });
}

// 点击按钮
function handleBatchDelete() {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的项目')
        return
    }

    const ids = selectedRows.value.map(item => item.id)

    ElMessageBox.confirm(`确定批量删除这${ids.join(',')}项目?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        console.log(11111, '------');
        console.log(ids);
        userdel(ids).then(res => {
            console.log(res);
            ElMessage.success('删除成功')
            fetchData()
        })
    }).catch(() => {
    })
}

function del(id: number) {
    userdel({ id }).then(() => {
        ElMessage.success('删除成功')
        fetchData()
    }).catch(() => {
        ElMessage.error('删除失败')
    })
}

const handleConfirm = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            if (title.value == '新增') {
                projectSave(ruleForm).then(res => {
                    // console.log(res, '88');
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    getproject()
                })
                    .catch(err => {
                        ElMessage.error('添加失败')
                    })
            } else if (title.value == '修改') {
                projectUpdate(ruleForm).then(res => {
                    // console.log(res, '5');
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    getproject()
                })
                    .catch(err => {
                        ElMessage.error('修改失败')
                    })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible.value = false

    if (!formEl) return
    formEl.resetFields()
}

// 删除
function getDelete(index: any) {
    let id = index ? [index] : delId.value
    console.log(id, 'id');

    ElMessageBox.confirm(
        `确定对[id=${id}]进行[删除]操作？`,
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        projectDelete(id).then(res => {
            ElMessage.success('删除成功')
            getproject()
        })
    })

}

// 处理时间戳
function formDate(value: any) {
    let data = new Date(value)
    // 年
    let yy = data.getFullYear()
    // 月
    let mm = data.getMonth() + 1
    // 日
    let dd = data.getDate()
    // 时
    let hh = data.getHours()
    // 分
    let m = data.getMinutes()
    // 秒
    let s = data.getSeconds()

    return `${yy}-${mm}-${dd}  ${hh}:${m}:${s}`
}
</script>

<style lang="scss" scoped>
.familyman {
    .search {
        .btn {
            color: #5d5c5c;
        }

        .btn2 {
            color: #fff;
        }

    }

:deep .table {
    .el-table thead th {
        background-color: #fff !important;
        color: #909399;
    }

    .cell {
        text-align: center !important;
        font-size: 12px !important;
    }
}
</style>